#include "mywidget.h"
#include "qscreen.h"
#include "onewidget.h"
#include<QHeaderView>
#include<QLabel>
#include<QTableWidget>
#include<QVBoxLayout>
#include<QHBoxLayout>
#include<QWidget>
#include<QSpacerItem>
#include<QSizePolicy>
#include<QDebug>
#include<QPushButton>
#include<QGroupBox>
#include<QApplication>
#include<QWidget>
#include<QThread>
#define MYLOG qDebug() << "[" << __FILE__ << ":" << __LINE__ << ":" << QThread::currentThread() << __func__ << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz")<< "]"
MyWidget::MyWidget(QWidget *parent) : QWidget(parent,Qt::WindowStaysOnTopHint)
{

  widget = new QWidget(this);


  //获取屏幕属性
  QScreen *screen = QGuiApplication::primaryScreen();

  scalex = screen->size().width();


  //比例系数
  labelXY = scalex/5.5;

//  currentWidth = labelXY;


  createTable();

  create();

  connect(clearButton,SIGNAL(clicked()),this,SLOT(clearBtn()));

  connect(checkButton,SIGNAL(clicked()),this,SLOT(checkBtn()));

  connect(this,SIGNAL(mySignal(const QList<QPointF>&)),targetSheet,SLOT(updateHoles(const QList<QPointF>&)));
}

MyWidget::~MyWidget()
{
  if(targetSheet != nullptr)
    {
      delete targetSheet;
    }
  targetSheet = nullptr;

  if(tableWidget != nullptr)
    {
      delete tableWidget;
    }
  tableWidget = nullptr;

  if(widget != nullptr)
    {
      delete widget;
    }
  widget = nullptr;

  if(checkWidget != nullptr)
    {
      delete checkWidget;
    }
  checkWidget = nullptr;

    delete labelBaHao;
  labelBaHao = nullptr;
    delete labelBattery;
  labelBattery = nullptr;
    delete labelName;
  labelName = nullptr;
    delete labelSum;
  labelSum = nullptr;
    delete zhongDanShu;
  zhongDanShu = nullptr;
    delete clearButton;
  clearButton = nullptr;
}



void MyWidget::create()
{
  //主界面外观设置
  this->resize(1200,840);
  this->setWindowTitle("靶标显示系统");
  this->setWindowIcon(QIcon(":/source/app-icon.gif"));
  this->setFixedSize(this->width(),this->height());

  QFont font;
  font.setPixelSize(14);
  font.setBold(true);
  font.setFamily("微软雅黑");



  QLabel *label_name = new QLabel("姓名:",widget);
//  label_name->setFont(QFont(QString::asprintf("Cambria Math"),(scalex+scaley)*14, QFont::Black));
  label_name->setFont(font);

  QLabel *label_baHao = new QLabel("靶位号:",widget);
//  label_baHao->setFont(QFont(QString::asprintf("Cambria Math"),(scalex+scaley)*14,  QFont::Black));
  label_baHao->setFont(font);

  QLabel *label_allHuanShu = new QLabel("总环数:",widget);
//  label_allHuanShu->setFont(QFont(QString::asprintf("Cambria Math"), (scalex+scaley)*14, QFont::Black));
  label_allHuanShu->setFont(font);

  labelName = new QLabel(widget);
//  labelName->setFont(QFont(QString::asprintf("Cambria Math"), (scalex+scaley)*14, QFont::Black));
  labelName->setFont(font);
  labelBaHao = new QLabel(QString::number(index),widget);
//  labelBaHao->setFont(QFont(QString::asprintf("Cambria Math"), (scalex+scaley)*14, QFont::Black));
  labelBaHao->setFont(font);
  labelSum = new QLabel("0",widget);
//  labelSum->setFont(QFont(QString::asprintf("Cambria Math"), (scalex+scaley)*14, QFont::Black));
  labelSum->setFont(font);

  //中靶数
  QLabel *zhongDan = new QLabel("中靶数: ",widget);
//  zhongDan->setFont(QFont(QString::asprintf("Cambria Math"), (scalex+scaley)*14, QFont::Black));
  zhongDan->setFont(font);
  zhongDanShu = new QLabel("0",widget);
//  zhongDanShu->setFont(QFont(QString::asprintf("Cambria Math"), (scalex+scaley)*14, QFont::Black));
  zhongDanShu->setFont(font);

  //电压值
  labelBattery = new QLabel("0 V",widget);
//  labelBattery->setFont(QFont(QString::asprintf("Cambria Math"), (scalex+scaley)*14, QFont::Black));
  labelBattery->setFont(font);
  QLabel *batteryLabel = new QLabel("靶位电压:",widget);
//  batteryLabel->setFont(QFont(QString::asprintf("Cambria Math"), (scalex+scaley)*14, QFont::Black));
  batteryLabel->setFont(font);

  //弹簧
  QSpacerItem *h_spacer = new QSpacerItem(10,10,QSizePolicy::Minimum,QSizePolicy::Minimum);
  //  QSpacerItem *v_spacer = new QSpacerItem(10,10,QSizePolicy::Minimum,QSizePolicy::Minimum);

  QHBoxLayout *h_layout_name = new QHBoxLayout;
  QHBoxLayout *h_layout_baHao = new QHBoxLayout;

  QHBoxLayout *h_zhongDan = new QHBoxLayout;
  QHBoxLayout *h_allSum = new QHBoxLayout;

  //名字布局
  h_layout_name->addWidget(label_name);
  h_layout_name->addWidget(labelName);

  //靶号布局
  h_layout_baHao->addWidget(label_baHao);
  h_layout_baHao->addWidget(labelBaHao);

  h_zhongDan->addWidget(zhongDan);
  h_zhongDan->addWidget(zhongDanShu);

  h_allSum->addWidget(label_allHuanShu);
  h_allSum->addWidget(labelSum);

  //中弹水平布局
  QHBoxLayout *h_zhongdan_allsum = new QHBoxLayout;
  h_zhongdan_allsum->addLayout(h_zhongDan);
  h_zhongdan_allsum->addItem(h_spacer);
  h_zhongdan_allsum->addLayout(h_allSum);

  //电压标签水平布局
  QHBoxLayout *h_layout_battery_value = new QHBoxLayout;
  h_layout_battery_value->addWidget(batteryLabel);
  h_layout_battery_value->addWidget(labelBattery);
  h_layout_battery_value->addItem(h_spacer);

//  setStyleSheet(
//      "QLabel{color:black;font-weight: simsun;font-bold:14px; font-bold:14px;}");

  //清除按钮布局
  QHBoxLayout *h_layout_clear_btn = new QHBoxLayout;
  clearButton = new QPushButton("清除记录",widget);
//    clearButton->setFont(font);
clearButton->setFixedSize(110,50);
  clearButton->setStyleSheet("QPushButton{width: 100px;height: 100px;border: 1px solid green;border-radius: 23px;background-color: #00ff7f;}""QPushButton:pressed{background:white;}");

//  clearButton->setFixedSize(scalex*130,scaley*50);

  checkButton = new QPushButton("二次校准",widget);
//    checkButton->setFont(font);
  checkButton->setStyleSheet("QPushButton{width: 100px;height: 100px;border: 1px solid green;border-radius: 23px;background-color: #00ff7f;}""QPushButton:pressed{background:white;}");
  checkButton->setFixedSize(110,50);

  h_layout_clear_btn->addItem(h_spacer);
  h_layout_clear_btn->addWidget(clearButton);

  h_layout_clear_btn->addItem(h_spacer);
  h_layout_clear_btn->addWidget(checkButton);
  h_layout_clear_btn->addItem(h_spacer);

  //右侧总布局
  QVBoxLayout *v_layout = new QVBoxLayout(widget);

  v_layout->addLayout(h_layout_name);

  v_layout->addLayout(h_layout_baHao);

  v_layout->addWidget(tableWidget);

  v_layout->addLayout(h_zhongdan_allsum);

  v_layout->addLayout(h_layout_battery_value);

  v_layout->addLayout(h_layout_clear_btn);

  widget->setLayout(v_layout);

  //在主界面中创建两个对象
  targetSheet = new TargetSheet(BulletSizeOne,this);

  //详细信息界面
  QHBoxLayout *h_layout = new QHBoxLayout(this);
  h_layout->addWidget(targetSheet);
  h_layout->addItem(h_spacer);
  h_layout->addWidget(widget);

  setLayout(h_layout);



  setStyleSheet(
        "QLabel,QPushButton{color:black;font-weight: simsun; font-family: 微软雅黑;font-bold;}");
}

void MyWidget::createTable()
{
  tableWidget = new QTableWidget(widget);
  tableWidget->setRowCount(BulletNumber);
  tableWidget->setColumnCount(3);
  //  tableWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

  //隐藏垂直表头
  QHeaderView *header1 =   tableWidget->verticalHeader();
  header1->setHidden(true);

  tableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section{font:19pt '宋体';};");
  tableWidget->setFixedSize(330,545);
  QStringList strList;
  strList<<tr("弹序")<<tr("环数")<<tr("方向");
  tableWidget->setHorizontalHeaderLabels(strList);
  tableWidget->setColumnWidth(0,110);
  tableWidget->setColumnWidth(1,100);
  tableWidget->setColumnWidth(2,100);

  for(int i = 0;i<BulletNumber;i++)
    {
      tableWidget->setRowHeight(i,50);

    }
  //  tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
  tableWidget->setStyleSheet("QTableWidget{width: 100px;height: 100px;border: 1px solid green;background: white;}"
                             "QScrollBar:vertical{max-width: 10px;max-height:10px;}"
                             "QScrollBar:horizontal{max-width: 10px;max-height:10px;}"
                             "QTableWidgetItem{color:black;font-size:25px;font-weight: simsun; font-family: 微软雅黑;font-bold;}");

}


//更新子弹列表
void MyWidget::passHolesData(const QMap<int,QVector<OneTaregtBullet>>& data)
{
//  int sum = 0,zhongBa = 0;
//  int bulletsNumber = data.size();

//  //只显示30发子弹
//  if(bulletsNumber > BulletNumber){
//      bulletsNumber = BulletNumber;
//  }

//  QVector<QPointF>   holesVector = {};

//  tableWidget->setRowCount(0);

      int sum = 0,zhongBa = 0;
      int msgSize = data[index].size();

      QList<QPointF>   onlyHoleList = {};
      QVector<OneTaregtBullet>datas = data[index];

      tableWidget->setRowCount(0);

      if(msgSize > BulletNumber)
        {
          msgSize = BulletNumber;
        }

      for(int i = 0;i < msgSize;i++)
        {
          tableWidget->insertRow(i);
          //待完善
          //      user_name = data[i].user_name;
          //      labelName->setText(user_name);



          sum += datas[i].cylinder_number;

          QTableWidgetItem *danXu = new QTableWidgetItem;
          danXu->setText(QString::number(i + 1));
          danXu->setTextAlignment(Qt::AlignCenter);
          danXu->setFont(QFont(QString::asprintf("Cambria Math"), 16, QFont::Black));

          QTableWidgetItem *huanShu = new QTableWidgetItem;
          huanShu->setText(QString::number(i + 1));
          huanShu->setTextAlignment(Qt::AlignCenter);
          huanShu->setFont(QFont(QString::asprintf("Cambria Math"), 16, QFont::Black));

          QTableWidgetItem *direction = new QTableWidgetItem;
          direction->setText(QString::number(i + 1));
          direction->setTextAlignment(Qt::AlignCenter);
          direction->setFont(QFont(QString::asprintf("Cambria Math"), 16, QFont::Black));

          if(datas[i].direction == -1)
            {
              danXu->setForeground(QColor(Qt::red));
              huanShu->setText(QString::asprintf("脱靶"));
              huanShu->setForeground(QColor(Qt::red));
              direction->setText(QString::asprintf("0"));
            }else{
              onlyHoleList.append(QPointF(datas[i].x,801 - datas[i].y));

              huanShu->setText(QString::number(datas[i].cylinder_number));
              direction->setText(QString::number(datas[i].direction));
              zhongBa++;
            }

          huanShu->setTextAlignment(Qt::AlignCenter);
          huanShu->setFont(QFont(QString::asprintf("Cambria Math"), 16, QFont::Black));
          direction->setTextAlignment(Qt::AlignCenter);
          direction->setFont(QFont(QString::asprintf("Cambria Math"), 16, QFont::Black));

          tableWidget->setItem(i,0,danXu);

          tableWidget->setItem(i,1,huanShu);
          tableWidget->setItem(i,2,direction);
        }

      zhongDanShu->setNum(zhongBa);

      labelSum->setNum(sum);

      emit mySignal(onlyHoleList);

      if(msgSize != after_rows)
        {
          // 将表格滚动到最后一行
          tableWidget->scrollToBottom();
        }
      //记录上次行数
      after_rows = msgSize;

}


void MyWidget::passName(const QVector<Target_Info_Table> &data, int a)
{
  for(int i = 0;i < data.size();i++)
    {
      if(index == data[i].addr)
        {

          user_name = data[i].user_name;
          labelName->setText(user_name);
          return ;
        }
    }

}

//设置电量信息
void MyWidget::passBatteryData(const QVector<double> &msg)
{
  if(index > 0 && index < 22)
    {
      labelBattery->setNum(msg[index]);
    }

}


//获取当前点击的item
void MyWidget::getIndex(int msg)
{
  index = msg ;

  //更新当前靶号
  labelBaHao->setNum(index);
}

void MyWidget::clearBtn()
{
  emit mySignalBtn();
}



//二次校准
void MyWidget::checkBtn()
{

  if(!checkWidget){
      checkWidget = new QWidget();
      checkWidget->setWindowTitle("手动校准");
      checkWidget->setWindowIcon(QIcon(":/source/app-icon.gif"));
      checkWidget->setFixedSize(checkWidget->x(),checkWidget->y());

      //顶层模式
      checkWidget->setWindowFlags(Qt::Window | Qt::WindowStaysOnTopHint);
      //透明状态范围0-1
      checkWidget->setWindowOpacity(0.95);
//      checkWidget->setAttribute(Qt::WA_TranslucentBackground);
      checkWidget->move(this->x() + this->width(),this->y() + this->height() / 2);
//      checkWidget->setStyleSheet("background-color: white;");

      QPushButton *upBtn = new QPushButton(checkWidget);
      upBtn->setFixedSize(80,80);
      upBtn->setIconSize(QSize(80,80));
      upBtn->setIcon(QIcon(":/source/up-yellow.jpeg"));

      //设置定时器，每隔MoveSpeed时间后调用连接的槽函数函数
      upTimer = new QTimer(this);
      upTimer->setInterval(MoveSpeed);

      connect(upTimer,&QTimer::timeout,this,[&](){
          curY = curY - 2;
          emit checkYSignal(curY);
        });

      //长按开启定时器
      connect(upBtn,&QPushButton::pressed,this,[&](){
          upTimer->start();
        });

      //松开暂停
      connect(upBtn,&QPushButton::released,this,[&](){
          upTimer->stop();
        });

      QPushButton *downBtn = new QPushButton(checkWidget);
      downBtn->setFixedSize(80,80);
      downBtn->setIconSize(QSize(80,80));
      downBtn->setIcon(QIcon(":/source/down-yellow.jpeg"));

      downTimer = new QTimer(this);
      downTimer->setInterval(MoveSpeed);

      connect(downTimer,&QTimer::timeout,this,[&](){
          curY = curY + 2;
          emit checkYSignal(curY);
        });

      //长按开启定时器
      connect(downBtn,&QPushButton::pressed,this,[&](){
          downTimer->start();
        });

      //松开暂停
      connect(downBtn,&QPushButton::released,this,[&](){
          downTimer->stop();
        });

      QPushButton *leftBtn = new QPushButton(checkWidget);
      leftBtn->setFixedSize(80,80);
      leftBtn->setIconSize(QSize(80,80));
      leftBtn->setIcon(QIcon(":/source/left-yellow.jpeg"));

      leftTimer = new QTimer(this);
      leftTimer->setInterval(MoveSpeed);

      connect(leftTimer,&QTimer::timeout,this,[&](){
          curX = curX - 2;
          emit checkXSignal(curX);
        });

      //长按开启定时器
      connect(leftBtn,&QPushButton::pressed,this,[&](){
          leftTimer->start();
        });

      //松开暂停
      connect(leftBtn,&QPushButton::released,this,[&](){
          leftTimer->stop();
        });

      QPushButton *rightBtn = new QPushButton(checkWidget);
      rightBtn->setFixedSize(80,80);
      rightBtn->setIconSize(QSize(80,80));
      rightBtn->setIcon(QIcon(":/source/right-yellow.jpeg"));

      rightTimer = new QTimer(this);
      rightTimer->setInterval(MoveSpeed);

      connect(rightTimer,&QTimer::timeout,this,[&](){
          curX = curX + 2;
          emit checkXSignal(curX);
        });

      //长按开启定时器
      connect(rightBtn,&QPushButton::pressed,this,[&](){
          rightTimer->start();
        });

      //松开暂停
      connect(rightBtn,&QPushButton::released,this,[&](){
          rightTimer->stop();
        });

      QPushButton *midBtn = new QPushButton("校准完毕",checkWidget);
      midBtn->setFixedSize(80,80);
      midBtn->setFont(QFont(QString::asprintf("Cambria Math"), 10, QFont::Black));
      midBtn->setStyleSheet("QPushButton{width: 100px;height: 100px;border: 1px solid green;font-family: 微软雅黑;border-radius: 15px;background-color: #00ffff}""QPushButton:pressed{background:white;}");

      QVBoxLayout *v_layout = new QVBoxLayout;
      v_layout->addWidget(upBtn);
      v_layout->addWidget(midBtn);
      v_layout->addWidget(downBtn);

      QHBoxLayout *h_layout = new QHBoxLayout;

      h_layout->addWidget(leftBtn);
      h_layout->addLayout(v_layout);
      h_layout->addWidget(rightBtn);
      checkWidget->setLayout(h_layout);

      connect(this,SIGNAL(checkXSignal(int)),targetSheet,SLOT(getX(int)));
      connect(this,SIGNAL(checkYSignal(int)),targetSheet,SLOT(getY(int)));

      connect(upBtn,&QPushButton::clicked,this,[&](){
          curY = curY - 2;
          emit checkYSignal(curY);
        });

      connect(downBtn,&QPushButton::clicked,this,[&](){
          curY = curY + 2;
          emit checkYSignal(curY);
        });

      connect(leftBtn,&QPushButton::clicked,this,[&](){
          curX = curX - 2;
          emit checkXSignal(curX);
        });

      connect(rightBtn,&QPushButton::clicked,this,[&](){
          curX = curX + 2;
          emit checkXSignal(curX);
        });

      connect(midBtn,&QPushButton::clicked,this,[&](){
          emit checkXandY(index,-curX,curY);

          curX = 0;
          curY = 0;
          emit checkXSignal(curX);
          emit checkYSignal(curY);


          emit checkXandY(index,-curX,curY);
          checkWidget->close();
        });
      connect(checkWidget,&QWidget::close,this,[&](){
          emit checkXandY(index,-curX,curY);

          curX = 0;
          curY = 0;
          emit checkXSignal(curX);
          emit checkYSignal(curY);
        });
    }
  checkWidget->show();
}



